package org.chen.wordwave.tools.words;

import androidx.annotation.Nullable;

import org.chen.wordwave.bean.FavoriteWords;
import org.chen.wordwave.bean.PageWord;
import org.chen.wordwave.bean.Words;
import org.chen.wordwave.init.WordInit;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WordsUtils {
    public static List<PageWord> getFlyerWords(@Nullable Integer size){

        if (size==null){
            size = 48;
        }

        List<PageWord> pageWords =new ArrayList<>();
        List<Words> words = LitePal.findAll(Words.class);
        for (int i=0;i<size;i++){
            List<Integer> indexes=getThreeRandomIndex(words.size(),i);
            if (LitePal.where("wordsId = ? and email = ?",String.valueOf(words.get(i).getId()),WordInit.userInfo.getEmail()).findFirst(FavoriteWords.class)!=null){
                pageWords.add(new PageWord(words.get(indexes.get(0)).getChinese(),words.get(indexes.get(1)).getChinese(),words.get(indexes.get(2)).getChinese(),words.get(i),true));

            }else {
                pageWords.add(new PageWord(words.get(indexes.get(0)).getChinese(),words.get(indexes.get(1)).getChinese(),words.get(indexes.get(2)).getChinese(),words.get(i),false));
            }
        }
        return pageWords ;
    }


    private static List<Integer> getThreeRandomIndex(int maxIndex,int nowIndex){
        Random random=new Random();
        List<Integer> indexes=new ArrayList<>();
        int index1=0;
        do {
            index1=random.nextInt(maxIndex);
        }while (index1==nowIndex);
        indexes.add(index1);
        int index2=0;
        do {
            index2=random.nextInt(maxIndex);
        }while (index2==nowIndex||index2==indexes.get(0));
        indexes.add(index2);

        int index3=0;
        do {
            index3=random.nextInt(maxIndex);
        }while (index3==nowIndex||index3==indexes.get(0)||index3==indexes.get(1));
        indexes.add(index3);

        return indexes;
    }

    public static Object getFlWords() {
        List<PageWord> pageWords =new ArrayList<>();
        List<Words> words = LitePal.findAll(Words.class);
        for (int i=0;i<words.size();i++){
            List<Integer> indexes=getThreeRandomIndex(words.size(),i);

            if (LitePal.where("wordsId = ? and email = ?",String.valueOf(words.get(i).getId()), WordInit.userInfo.getEmail()).findFirst(FavoriteWords.class)!=null){
                pageWords.add(new PageWord(words.get(indexes.get(0)).getEnglish(),words.get(indexes.get(1)).getEnglish(),words.get(indexes.get(2)).getEnglish(),words.get(i),true));

            }else {
                pageWords.add(new PageWord(words.get(indexes.get(0)).getEnglish(),words.get(indexes.get(1)).getEnglish(),words.get(indexes.get(2)).getEnglish(),words.get(i),false));


            }
        }
        return pageWords ;

    }
}
